<?php

namespace app\api\controller;

/**
 * Token接口
 */
class TaskWechat extends Taskbase{

    protected $noNeedLogin = ["login","getuserinfo","reguser"];
    protected $noNeedRight = '*';
    protected $app;
    protected function _initialize()
    {
        parent::_initialize();

    }
    //用户信息
    public function getuserinfo(){
        // $code = $this->request->request("code");
  $oauth = $this->app->oauth;

          // 获取 OAuth 授权结果用户信息、
  try {
      $user = $oauth->user()->toArray();
  }catch (AuthorizeFailedException $e){
      $err_arr = json_decode(str_replace("Authorize Failed: ","",$e->getMessage()),true);
     // print_r(json_decode($errstr,true));
      return json(["status"=>0,"msg"=>"授权错误：".$err_arr["errmsg"],"data"=>"GU0001"]);
  }
  $wechat_user =  WechatUser::where("openid",$user["id"])->find();
  if(!$wechat_user){
      $save_data = [
          "openid" => $user["id"],
          "nickname" => $user["name"] ,
          "sex" => $user["original"]["sex"],
          "language" => $user["original"]["language"],
          "city" => $user["original"]["city"],
          "province" => $user["original"]["province"],
          "country" => $user["original"]["country"],
          "headimgurl" => $user["original"]["headimgurl"],
      ];

      //创建微信用户
      $wechat_user = WechatUser::create($save_data);
      //创建用户表用户
      $ret = $this->auth->register($user["id"], md5($user["id"].$user["name"].$user["original"]["sex"]));
      if(!$ret){
              return json(["status"=>0,"msg"=>"用户创建失败-1".$this->auth->getError(),"data"=>"GU0002"]);
      }
      $user_info = $this->auth->getUser();

      $wechat_user->user_id = $user_info["id"];
      $wechat_user->save();
  }else{
      if($wechat_user->user_id){
          $this->auth->direct($wechat_user->user_id);
          $user_info = $this->auth->getUser();
      }else{
          $ret = $this->auth->register($wechat_user->id, md5($wechat_user->id.$wechat_user->nickname.$wechat_user->sex));
          if(!$ret){
              return json(["status"=>0,"msg"=>"用户创建失败-2".$this->auth->getError(),"data"=>"GU0002"]);
          }
          $user_info = $this->auth->getUser();
          $wechat_user->user_id = $user_info["id"];
          $wechat_user->save();
      }
  }
  $wechat_user =  WechatUser::where("openid",$user["id"])->find();
  $token = $this->auth->getToken();
  cache("USER_".$token,serialize($wechat_user));
  return json(["status"=>"1","msg"=>"用户信息获取成功","data"=>$token,"wechat_user"=>[
      "nickname"=>$wechat_user->nickname,
      "user_id"=>$wechat_user->user_id,
      "mobile"=>$wechat_user->mobile,
      "sex"=>$wechat_user->sex,
      "language"=>$wechat_user->language,
      "province"=>$wechat_user->province,
      "city"=>$wechat_user->city,
      "country"=>$wechat_user->country,
      "headimgurl"=>$wechat_user->headimgurl,
      "sex_text"=>$wechat_user->sex_text,
      "createtime"=>$wechat_user->createtime,
      "updatetime"=>$wechat_user->updatetime,
  ]]);
}

}